//
//  MYGMyReportDetailViewController.swift
//  MYDoctor
//
//  Created by Denny on 2024/4/16.
//

import UIKit
import WebKit
class MYGMyReportDetailViewController: MYGBaseController {
    @IBOutlet weak var webHeight: NSLayoutConstraint!
    @IBOutlet weak var webView: WKWebView!
    @IBOutlet weak var titleLB: UILabel!
    @IBOutlet weak var timeLB: UILabel!
    @IBOutlet weak var unitLB: UILabel!
    @IBOutlet weak var avatar: UIImageView!
    var id = ""
    var model = MYGArticleDetailModel()
    override func viewDidLoad() {
        super.viewDidLoad()
        getData()
        navigationBarShow()
        self.title = "报道详情"
        self.webView.navigationDelegate = self
        self.webView.scrollView.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil)
    }
    
    deinit {
        self.webView.scrollView.removeObserver(self, forKeyPath: "contentSize")
    }
    
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
           if keyPath == "contentSize" {
               if self.model.isLoad == true {return}
               var height = self.webView.scrollView.contentSize.height
               print("height = \(height)")
               if self.model.content.count == 0 {
                   height = 0
               }
               
               self.webHeight.constant = height
           }
       }
    func getData() {
        MYGLoading.show()
        MYGNetwork<MYGMeAPI, MYGArticleDetailModel>.request(target: .articlelDetail(param: [
            "id":id])) {[weak self] item in
                self?.bindData(item)
                MYGLoading.hide()
            } failed: { _, error in
                MYGLoading.hide()
                MMYGHUD.showToast(text: error)
            }
    }

    func bindData(_ data: MYGArticleDetailModel) {
        model = data
        self.titleLB.text = data.title
        self.webView.loadHTMLString(data.content, baseURL: nil)
        self.timeLB.text = data.updated_at
        self.avatar.sd_setImage(with: URL(string: data.img), placeholderImage: UIImage.init(named: "head"))
        self.unitLB.text = data.from
    }
}

extension MYGMyReportDetailViewController:WKNavigationDelegate {
    public func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        webView.evaluateJavaScript("document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '230%'", completionHandler: nil)
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: {
            self.model.isLoad = true
        })
    }
}
